<template>
  <div class="app-container">
    <div style="border: 1px gainsboro solid;padding: 10px 10px 10px 30px">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" >
        <div style="display: inline-block;width: 300px;">
          <el-form-item label="仓库" prop="scId">
            <el-select v-model="form.scId" placeholder="全部" clearable :style="{width: '100%'}" @change="getTblSaleOrderDetailList(form.scId)">
              <el-option v-for="(item, index) in StoreCenterInfoList" :key="index" :label="item.name"
                         :value="item.id" >{{item.name}}</el-option>
            </el-select>
          </el-form-item>
        </div>
        <div style="display: inline-block;">
          <el-form-item label="预先盘点状态" prop="customerName">
            <el-checkbox v-model="checkbox1" disabled>初盘</el-checkbox>
            <el-checkbox v-model="checkbox2" @input="updateStatus" :disabled="checkbox3">复盘</el-checkbox>
            <el-checkbox v-model="checkbox3" @input="updateStatus" :disabled="!checkbox2">抽盘</el-checkbox>
          </el-form-item>
        </div>
        <br>
        <div style="display: inline-block;">
          <el-form-item label="备注" prop="description">
            <el-input
              type="textarea"
              :rows="2"
              v-model="form.description"
              style="width: 800px;"
            />
          </el-form-item>
        </div>
      </el-form>
    </div>

    <div style="border: 1px gainsboro solid;margin-top: 5px">
      <el-table height="400px" v-loading="loading" :data="this.preTakeStockSheetDetailList" @selection-change="handleSelectionChange">
<!--        <el-table-column label="商品编号" align="left" prop="baseDataProduct.code" width="100px"/>-->
<!--        <el-table-column label="商品名称" align="left" prop="baseDataProduct.name" width="150px"/>-->
<!--        <el-table-column label="单位" align="left" prop="baseDataProduct.unit" width="100px"/>-->
<!--        <el-table-column label="规格" align="left" prop="baseDataProduct.spec" width="100px"/>-->
<!--        <el-table-column label="商品类目" align="left" prop="baseDataProduct.baseDataProductCategory.name" width="100px"/>-->
<!--        <el-table-column label="商品品牌" align="left" prop="baseDataProduct.baseDataProductBrand.name" width="100px"/>-->
<!--        <el-table-column label="商品库存" align="left" prop="baseDataProduct.stockNum" width="100px">-->
<!--          <template slot-scope="scope">-->
<!--            <span>{{scope.row.baseDataProduct.stockNum || 0}}</span>-->
<!--          </template>-->
<!--        </el-table-column>-->

        <!--        商品数据-->
        <el-table-column label="商品编号" align="left" prop="baseDataProduct.code" width="100px" v-if="purchaseType===0 && preTakeStockSheetDetailList.length>0"/>
        <el-table-column label="商品名称" align="left" prop="baseDataProduct.name" width="200px" v-if="purchaseType===0 && preTakeStockSheetDetailList.length>0"/>
        <el-table-column label="单位" align="left" prop="baseDataProduct.unit" width="100px" v-if="purchaseType===0 && preTakeStockSheetDetailList.length>0"/>
        <el-table-column label="规格" align="left" prop="baseDataProduct.spec" width="100px" v-if="purchaseType===0 && preTakeStockSheetDetailList.length>0"/>
        <el-table-column label="商品类目" align="left" prop="baseDataProduct.baseDataProductCategory.name" width="100px" v-if="purchaseType===0 && preTakeStockSheetDetailList.length>0"/>
        <el-table-column label="商品品牌" align="left" prop="baseDataProduct.baseDataProductBrand.name" width="100px" v-if="purchaseType===0 && preTakeStockSheetDetailList.length>0"/>
        <el-table-column label="商品库存" align="left" prop="baseDataProduct.stockNum" width="100px" v-if="purchaseType===0 && preTakeStockSheetDetailList.length>0"/>

        <!--        物料数据-->
        <el-table-column label="物料编号" align="left" prop="material.materialCode" width="100px" v-if="purchaseType===1 && preTakeStockSheetDetailList.length>0"/>
        <el-table-column label="物料名称" align="left" prop="material.materialName" width="150px" v-if="purchaseType===1 && preTakeStockSheetDetailList.length>0"/>
        <el-table-column label="物料类型" align="left" prop="material.typeName" width="100px" v-if="purchaseType===1 && preTakeStockSheetDetailList.length>0"/>
        <el-table-column label="规格型号" align="left" prop="material.specification" width="150px" v-if="purchaseType===1 && preTakeStockSheetDetailList.length>0"/>
        <el-table-column label="分类名称" align="left" prop="material.categoryName" width="100px" v-if="purchaseType===1 && preTakeStockSheetDetailList.length>0"/>
        <el-table-column label="单位" align="left" prop="material.purchaseUnitName" width="100px" v-if="purchaseType===1 && preTakeStockSheetDetailList.length>0"/>
        <el-table-column label="物料库存" align="left" prop="stockQuantity" width="100px" v-if="purchaseType===1 && preTakeStockSheetDetailList.length>0"/>

        <el-table-column label="初盘数量" align="left" prop="firstNum" width="100px">
          <template slot-scope="scope">
            <el-input v-model="scope.row.firstNum" @input="() => updateDifference(scope.row)" v-if="form.takeStatus<=2 && checkbox1"/>
          </template>
        </el-table-column>
        <el-table-column label="复盘数量" align="left" prop="secondNum" width="100px">
          <template slot-scope="scope">
            <el-input v-model="scope.row.secondNum" @input="() => updateDifference(scope.row)" v-if="form.takeStatus>0 && checkbox2"/>
          </template>
        </el-table-column>
        <el-table-column label="抽盘数量" align="left" prop="randNum" width="100px">
          <template slot-scope="scope">
            <el-input v-model="scope.row.randNum" @input="() => updateDifference(scope.row)" v-if="form.takeStatus===2 && checkbox3"/>
          </template>
        </el-table-column>
        <el-table-column label="复盘初盘差异数量" align="left" prop="" width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.firstSecondDiff || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="复盘抽盘差异数量" align="left" prop="" width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.secondRandDiff || 0 }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div slot="footer" class="dialog-footer" style="text-align: center;margin: 5px">
      <el-button type="primary" @click="submitForm()">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </div>
</template>

<script>
import {parseTime} from "../../../utils/ruoyi";
import {listStoreCenterInfo} from "@/api/system/StoreCenterInfo";
import {listProductInfo} from "@/api/system/ProductInfo";
import {addSheet, getSheet, listSheet, updateSheet} from "@/api/system/PreTakeStockSheet";
import {listStock} from "@/api/system/stock";
import {listMaterialStock} from "@/api/system/MaterialStock";

export default {
  name: "orderAdd",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 商品选中数组
      ids: [],
      // 支付方式选中数组
      payIds: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,

      // 商品数据
      productList: [],
      //仓库数据
      StoreCenterInfoList:[],
      // 采购订单明细表格数据
      preTakeStockSheetDetailList: [],
      // 采购订单表格数据
      preTakeStockSheetList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        scName: null,
        customerName: null,
      },
      // 表单参数
      form: {
        id:null,
        code:null,
        scId:null,
        takeStatus:0,
        center:{
          name:''
        },
      },
      // 表单校验
       rules: {
        code: [
          { required: true, message: "编号不能为空", trigger: "blur" }
        ],
      },

      //商品框
      restaurants: [],
      state1: '',
      state2: '',
      // 查询参数
      productQueryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        name: null,
        shortName: null,
        skuCode: null,
        categoryId: null,
        brandId: null,
        productType: null,
        available: null,
        createTime: null,
      },
      //订单表ID数据
      preTakeStockSheetAllList:[],
      //订单详情表ID数据
      preTakeStockSheetDetailAllList:[],

      //盘点状态
      checkbox1:true,
      checkbox2:false,
      checkbox3:false,

      //详情类型
      purchaseType:null,
    };
  },
  created() {
    //仓库数据
    this.getStoreCenterInfoList();
    //盘点详情数据
    this.getTakeStockAllList();
    if (this.$route.query.id!=null){
      this.selectTakeStockSheet();
    }

    this.loading = false;
  },
  methods: {
    parseTime,
    /** 查询盘点详情 */
    selectTakeStockSheet() {
      const id = this.$route.query.id
      getSheet(id).then(response => {
        // 盘点赋值
        this.form = response.data;
        //盘点详情
        this.preTakeStockSheetDetailList = response.data.tblPreTakeStockSheetDetailList;

        if (this.form.takeStatus == 0){
          this.checkbox1 = true;
        }
        if (this.form.takeStatus == 1){
          this.checkbox1 = true;
          this.checkbox2 = true;
        }
        if (this.form.takeStatus == 2){
          this.checkbox1 = true;
          this.checkbox2 = true;
          this.checkbox3 = true;
        }

        for (let i = 0; i < this.preTakeStockSheetDetailList.length; i++) {
          this.updateDifference(this.preTakeStockSheetDetailList[i])
        }

        this.loading = false;
      });
    },

    /** 查询仓库列表 */
    getStoreCenterInfoList() {
      this.loading = true;
      listStoreCenterInfo({categoryType:1}).then(response => {
        this.StoreCenterInfoList = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.back();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

    /** 提交按钮 */
    submitForm() {
      if(this.formInfo()){
        if (this.form.id != null) {
          for (let i = 0; i < this.preTakeStockSheetDetailList.length; i++) {
            const newId = generateUniqueId(this.preTakeStockSheetDetailAllList);
            this.preTakeStockSheetDetailList[i].id=newId;
          }

          this.form.tblPreTakeStockSheetDetailList=this.preTakeStockSheetDetailList

          updateSheet(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.back();
          });
        } else {
          const newId = generateUniqueId(this.preTakeStockSheetAllList);
          var code = getOrderCode(this.preTakeStockSheetList);
          this.form.id=newId;
          this.form.code=code;
          for (var i = 0; i < this.preTakeStockSheetDetailList.length; i++) {
            this.preTakeStockSheetDetailList[i].sheetId=newId;
            this.preTakeStockSheetDetailList[i].orderNo=i+1
          }
          for (let i = 0; i < this.preTakeStockSheetDetailList.length; i++) {
            const newId = generateUniqueId(this.preTakeStockSheetDetailAllList);
            this.preTakeStockSheetDetailList[i].id=newId;
          }
          this.form.tblPreTakeStockSheetDetailList=this.preTakeStockSheetDetailList;
          this.form.createBy="系统管理员";
          this.form.createById="1";
          this.form.updateBy="系统管理员";
          this.form.updateById="1";

          addSheet(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.back();
          });
        }
      }
    },
    //提交表单验证
    formInfo(){
      if (this.form.scId==null){
        this.$modal.msgError("请选择仓库");
        return false;
      }else if (this.preTakeStockSheetDetailList.length<=0){
        this.$modal.msgError("请选择盘点商品");
        return false;
      }

      for (let i = 0; i < this.preTakeStockSheetDetailList.length; i++) {
        if (this.preTakeStockSheetDetailList[i].firstNum==null){
          this.$modal.msgError("请输入初盘数量");
          return false;
        }
        if (this.form.takeStatus>0 && this.preTakeStockSheetDetailList[i].secondNum==null){
          this.$modal.msgError("请输入复盘数量");
          return false;
        }
        if (this.form.takeStatus===2 && this.preTakeStockSheetDetailList[i].randNum==null){
          this.$modal.msgError("请输入抽盘数量");
          return false;
        }
      }

      return true;
    },
    /** 删除按钮操作 */
    handleDelete(name) {
      if(name=="detail") {
        if (this.ids.length === 0) {
          this.$message.warning('请选择要删除的行');
          return;
        }
        this.preTakeStockSheetDetailList = this.preTakeStockSheetDetailList.filter(item => !this.ids.includes(item.id));
        this.ids = [];
        this.getSumNumber(); // 重新计算合计
      }else {
        if (this.payIds.length === 0) {
          this.$message.warning('请选择要删除的行');
          return;
        }
        this.OrderPayTypeList = this.OrderPayTypeList.filter(item => !this.payIds.includes(item.id));
        this.payIds = [];
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/SettleInItem/export', {
        ...this.queryParams
      }, `SettleInItem_${new Date().getTime()}.xlsx`)
    },

    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.name.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },

    // 获取所有盘点详情数据ID
    getTakeStockAllList(){
      this.preTakeStockSheetAllList=[];
      this.preTakeStockSheetDetailAllList=[];
      var list=[];

      listSheet(null).then(response => {
        this.preTakeStockSheetList = response.rows;
        list=response.rows;

        for (var i=0;i<list.length;i++){
          this.preTakeStockSheetAllList.push(list[i].id)
          for (var j=0;j<list[i].tblPreTakeStockSheetDetailList.length;j++){
            this.preTakeStockSheetDetailAllList.push(list[i].tblPreTakeStockSheetDetailList[j].id);
          }
        }
      });
    },

    //根据复选框来改变当前状态
    updateStatus(){
      if(this.checkbox2){
        this.form.takeStatus=1
        for (let i = 0; i < this.preTakeStockSheetDetailList.length; i++) {
          this.preTakeStockSheetDetailList[i].secondNum=this.preTakeStockSheetDetailList[i].firstNum
        }
      }
      if (this.checkbox3){
        this.checkbox2=true
        this.form.takeStatus=2
        for (let i = 0; i < this.preTakeStockSheetDetailList.length; i++) {
          this.preTakeStockSheetDetailList[i].randNum=this.preTakeStockSheetDetailList[i].secondNum
        }
      }
    },

    // 自动计算差异值
    updateDifference(row) {
      // 复盘初盘差异 = firstNum - secondNum
      if (row.firstNum != null && row.secondNum != null) {
        const diff1 = row.firstNum - row.secondNum;
        this.$set(row, 'firstSecondDiff', diff1 === 0 ? 0 : Math.abs(diff1));
      }

      // 复盘抽盘差异 = secondNum - randNum
      if (row.secondNum != null && row.randNum != null) {
        const diff2 = row.secondNum - row.randNum;
        this.$set(row, 'secondRandDiff', diff2 === 0 ? 0 : Math.abs(diff2));
      }
    },

    // 商品列表
    async getTblSaleOrderDetailList(scId) {
      this.preTakeStockSheetDetailList=[]

      let type=1;
      for (let i = 0; i < this.StoreCenterInfoList.length; i++) {
        if (this.StoreCenterInfoList[i].id==scId){
          type=this.StoreCenterInfoList[i].categoryType;
          if (type==1){
            this.purchaseType=0
          }else {
            this.purchaseType=1
          }
        }
      }

      if (type==1){
        listStock({scId:scId}).then(response => {
          let list = response.rows.map(item => ({
            id: item.productId,
            name: item.productName,
            code: item.productCode,
            skuCode: item.skuCode,
            externalCode: item.externalCode,
            unit: item.unit,
            spec: item.spec,
            baseDataProductCategory:{
              name: item.productType
            },
            baseDataProductBrand:{
              name: item.productBrand
            },
            oriPrice: item.oriPrice,
            isGift: item.isGift,
            taxPrice: item.taxPrice,
            orderNum: item.orderNum,
            taxAmount: item.taxAmount,
            stockNum: item.stockNum,
            taxRate: item.taxRate,
            description: item.description
          }));

          for (let i = 0; i < list.length; i++) {
            this.preTakeStockSheetDetailList.push({
              baseDataProduct: list[i],
              id: '',
              sheetId: this.$route.query.id,
              productId: list[i].id,
              firstNum:list[i].stockNum||0,
              secondNum:null,
              randNum:null,
              orderNo: this.preTakeStockSheetDetailList.length,
            })
          }
        });
      }else {
        listMaterialStock({warehouseId:scId}).then( response=> {
          let list =response.rows;
          for (let i = 0; i < list.length; i++) {
            let num=list[i].material.materialType
            let name= num==1 ? "原材料" : num==2 ? "半成品" :num==3 ? "成品" : "辅料"
            list[i].material.typeName=name

            this.preTakeStockSheetDetailList.push({
              material: list[i].material,
              id: '',
              sheetId: this.$route.query.id,
              materialId: list[i].materialId,
              firstNum:list[i].stockQuantity||0,
              stockQuantity:list[i].stockQuantity,
              secondNum:null,
              randNum:null,
              orderNo: this.preTakeStockSheetDetailList.length,
            })
          }
        })
      }
    },
  },
  beforeRouteLeave(to, from, next) {
    // 设置一个标志，表示需要刷新数据
    to.meta.refresh = true;
    next();
  }
};

// ID生成
function generateUniqueId(existingIds) {
  const prefix = '18';
  const length = 19 - prefix.length;
  const characters = '0123456789';
  let uniqueId;

  do {
    uniqueId = prefix;
    for (let i = 0; i < length; i++) {
      uniqueId += characters.charAt(Math.floor(Math.random() * characters.length));
    }
  } while (existingIds.includes(uniqueId));

  return uniqueId;
}

//单号生成
function getOrderCode(list) {
  var date = new Date(),
    year = date.getFullYear(),
    month = date.getMonth() + 1, // 月份是从0开始的
    day = date.getDate();

// 如果月份或日期是个位数，在前面补0
  month = month < 10 ? '0' + month : month;
  day = day < 10 ? '0' + day : day;

  var time=year + '' + month + '' + day

  let type="PDYX";    //盘点预先
  var code=time+'0000000'
  var str1=code.slice(0,7)
  var str2=code.slice(7,)

  if (str2.slice(0,1)=="0"){
    str1=code.slice(0,6)
    str2=code.slice(6,)

    for (var i=0;i<list.length;i++){
      let listCode=list[i].code.slice(4,);
      if (listCode.slice(0, 8)===time){
        if (parseInt(listCode.slice(6,))>parseInt(str2)){
          code=listCode;
          str2=code.slice(6,)
        }
      }
    }
  }else {
    for (var i=0;i<list.length;i++){
      let listCode=list[i].code.slice(4,);
      if (listCode.slice(0, 8)===time){
        if (parseInt(listCode.slice(7,))>parseInt(str2)){
          code=listCode;
          str2=code.slice(7,);
        }
      }
    }
  }

  code=type+str1+(parseInt(str2)+1)

  return code.toString();
}
</script>


















